package email

import (
	"crypto/tls"
	"fmt"
	"github.com/jordan-wright/email"
	"github.com/spf13/viper"
	"log"
	"math/rand"
	"net/smtp"
	"strings"
	"time"
)

func GenValidateCode(width int) string {
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}
func SendMailQQ(emailaddr string) (setcode string) {

	mailUserName := viper.GetString("email.username") //邮箱账号
	mailPassword := viper.GetString("email.password") //邮箱授权码
	addr := "smtp.qq.com:465"                         //TLS地址
	host := "smtp.qq.com"                             //邮件服务器地址
	code := GenValidateCode(6)                        //发送的验证码
	Subject := "验证码发送测试"                              //发送的主题

	e := email.NewEmail()
	e.From = "Get <3194452409@qq.com>"
	e.To = []string{emailaddr}
	e.Subject = Subject
	e.HTML = []byte("你的验证码为：<h1>" + code + "</h1>")
	err := e.SendWithTLS(addr, smtp.PlainAuth("", mailUserName, mailPassword, host),
		&tls.Config{InsecureSkipVerify: true, ServerName: "smtp.qq.com"})
	if err != nil {
		fmt.Println("fail to send email")
		log.Fatal(err)
	}
	return code

}
func SendMailQQWithCode(emailaddr string, code string) (setcode string) {

	mailUserName := viper.GetString("email.username") //邮箱账号
	mailPassword := viper.GetString("email.password") //邮箱授权码
	addr := "smtp.qq.com:465"                         //TLS地址
	host := "smtp.qq.com"                             //邮件服务器地址 //发送的验证码
	Subject := "验证码发送mq"                              //发送的主题

	e := email.NewEmail()
	e.From = "Get <3194452409@qq.com>"
	e.To = []string{emailaddr}
	e.Subject = Subject
	e.HTML = []byte("你的验证码为：<h1>" + code + "</h1>")
	err := e.SendWithTLS(addr, smtp.PlainAuth("", mailUserName, mailPassword, host),
		&tls.Config{InsecureSkipVerify: true, ServerName: "smtp.qq.com"})
	if err != nil {
		fmt.Println("fail to send email")
		log.Fatal(err)
	}
	return code

}
